package com.cssw.fyzb.tps.service.sms.adapter;

import com.alibaba.fastjson.JSON;
import com.cssw.fyzb.tps.config.sms.ChuangLanSmsConfiguration;
import com.cssw.fyzb.tps.exception.BizException;
import lombok.Data;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Feng Chen
 */
@Component
public class ChuangLanSmsAdapter implements SmsAdapter {

    @Autowired
    private ChuangLanSmsConfiguration configuration;

    private static final Logger logger = LoggerFactory.getLogger(ChuangLanSmsAdapter.class);

    public ChuangLanSmsAdapter(ChuangLanSmsConfiguration configuration) {
        this.configuration = configuration;
    }

    @Override
    public void send(String mobile, String message) throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("account", configuration.getAccount());
        param.put("password", configuration.getPassword());
        param.put("msg", "【fy短视频】" + message);
        param.put("phone", mobile);
        param.put("report", "true");
        param.put("extend", "123");

        String json = JsonPost.send(configuration.getUrl(), param);
        logger.info(json);

        HttpResult result = JSON.parseObject(json, HttpResult.class);
        if (!"0".equals(result.getCode())) {
            throw new BizException(Integer.parseInt(result.getCode()), result.getErrorMsg());
        }
    }

    @Override
    public void send(String mobile, String signName, String code, String templateCode) throws Exception {

    }

    public ChuangLanSmsConfiguration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(ChuangLanSmsConfiguration configuration) {
        this.configuration = configuration;
    }

    @Data
    private static class HttpResult {

        private String code;
        private String msgId;
        private String time;
        private String errorMsg;

    }

    private static abstract class JsonPost {

        // 设置连接超时时间，单位毫秒。
        private static final int CONNECT_TIMEOUT = 6000;

        // 请求获取数据的超时时间(即响应时间)，单位毫秒。
        private static final int SOCKET_TIMEOUT = 3000;

        private JsonPost() {

        }

        public static String send(String url, Map<String, Object> param) throws Exception {
            CloseableHttpClient httpClient = null;

            try {
                httpClient = HttpClients.createDefault();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setConfig(
                        RequestConfig.custom()
                                .setConnectTimeout(CONNECT_TIMEOUT)
                                .setSocketTimeout(SOCKET_TIMEOUT)
                                .build()
                );

                packageHeader(httpPost);
                packageParam(httpPost, param);

                return execute(httpClient, httpPost);
            } finally {
                try {
                    if (httpClient != null) {
                        httpClient.close();
                    }
                } catch (IOException e) {
                    // ignore ...
                }
            }
        }

        private static void packageHeader(HttpRequestBase httpMethod) {
            httpMethod.setHeader("Content-type", "application/json");
        }

        private static void packageParam(HttpEntityEnclosingRequestBase httpMethod, Map<String, Object> param) {
            StringEntity requestEntity = new StringEntity(JSON.toJSONString(param), "UTF-8");
            requestEntity.setContentEncoding("UTF-8");
            httpMethod.setEntity(requestEntity);
        }

        private static String execute(CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
            CloseableHttpResponse httpResponse = null;
            try {
                // 执行请求
                httpResponse = httpClient.execute(httpMethod);

                // 获取返回结果
                if (httpResponse != null && httpResponse.getStatusLine() != null) {
                    return EntityUtils.toString(httpResponse.getEntity());
                }
                return null;
            } finally {
                if (httpResponse != null) {
                    try {
                        httpResponse.close();
                    } catch (IOException e) {
                        // ignore...
                    }
                }
            }
        }

    }


}
